<template>
  <div class="app-container">
    <el-select v-model="listQuery.relations" filterable placeholder="关系">
      <el-option v-for="item in menuTypeOptions" :key="item.key" :label="item.display_name" :value="item.key"
      ></el-option>
    </el-select>
    <el-select v-model="listQuery.type" filterable placeholder="查询模式">
      <el-option v-for="item in menuStatus" :key="item.key" :label="item.display_name" :value="item.key"></el-option>
    </el-select>
    <el-date-picker v-model="listQuery.start_at" placeholder="搜索开始时间" type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
    ></el-date-picker>
    <el-date-picker v-model="listQuery.end_at" placeholder="搜索结束时间" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
    ></el-date-picker>
    <el-button class="mb" icon="el-icon-search" type="primary" @click="getList">搜索</el-button>
    <el-button class="mb" type="primary" @click="getExcel">导出Excel</el-button>
    <!--    <a href="#" class="a_post"  @click="getExcelA">测试按钮</a>-->

    <el-table :data="menuList" :tree-props="{children: 'children', hasChildren: 'hasChildren'}" border row-key="id"
              style="margin-bottom: 20px;margin-top: 10px;"
    >
      <el-table-column label="时间" prop="add_time"></el-table-column>
      <el-table-column label="房间ID" prop="room_id"></el-table-column>
      <el-table-column label="用户ID" prop="user_code"></el-table-column>
      <el-table-column label="直播时长" prop="aaa"></el-table-column>
      <el-table-column label="房间流水" prop="amount"></el-table-column>
      <!--      <el-table-column min-width="280" label="操作">-->
      <!--        <template slot-scope="scope">-->
      <!--          <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row)" plain>-->
      <!--            查看详情-->
      <!--          </el-button>-->
      <!--&lt;!&ndash;          <cus-del-btn @ok="handleDelete(scope.row)"></cus-del-btn>&ndash;&gt;-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>
    <!-- 分页 -->
    <cus-pagination :limit.sync="listQuery.perPage" :page.sync="listQuery.page" :total="total" @pagination="getList"/>
    <!--    v-show="total>0"-->

    <el-dialog v-dialogDrag :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible"
               @close="handleDialogClose"
    >
      <el-form ref="dataForm" :model="form" :rules="rules" label-position="right" label-width="120px"
               style="width: 400px; margin: 0 auto;"
      >
        <el-form-item label="管理员姓名" prop="admin_account">
          <el-input v-model="form.admin_account" maxlength="50" placeholder="管理员姓名" show-word-limit/>
        </el-form-item>
        <el-form-item label="管理员密码" prop="password">
          <el-input v-model="form.password" placeholder="管理员密码"/>
        </el-form-item>
        <el-form-item label="厅的号码" prop="sociaty_no">
          <el-input v-model="form.sociaty_no" placeholder="厅的号码"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm()">
          确 认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { saveMenu, deleteMenu, treeMenu, updateMenu, cacheMenu, getExcel } from '@/api/hall/hallWater'
import fileDownload from 'js-file-download'
import treeTable from '@/components/TreeTable'
import { validateCh } from '@/utils/validate'
import md5 from 'js-md5'

// 常量title
const tempDesc = {
  'id': '',
  'parentId': '',
  'menu_key': '菜单key值',
  'menu_name': '名称',
  'level': '排序',
  'icon': '图标',
  'type': '类型',
  'status': '状态',
  'parent_id': '上级菜单'
}
const menuTypeOptions = [
  { key: '', display_name: '全部关系' },
  { key: '1', display_name: '直属' },
  { key: '2', display_name: '挂靠' }
]
const menuStatus = [
  { key: '', display_name: '全部查询模式' },
  { key: '1', display_name: '按天统计' },
  { key: '2', display_name: '按周统计' },
  { key: '3', display_name: '按月统计' }
]

export default {
  components: { treeTable },
  data() {
    const _validateCh = (rule, value, callback) => {
      if (!!value && validateCh(value)) {
        callback(new Error('不能包含中文'))
      }
      callback()
    }
    return {
      expandAll: false,
      // expandAll: true, // 是否全部展开
      expandAllTitle: '展开全部',
      tempDesc: tempDesc,
      listLoading: true,
      total: 0,
      listQuery: {
        page: 1,
        perPage: 10,
        type: '',
        start_at: '',
        end_at: '',
      },
      columns: [
        {
          label: '菜单名称',
          key: 'title',
          width: 220,
          expand: true,
          align: 'left',
          headerAlign: 'center'
        },
        {
          label: '菜单key值',
          key: 'menu_key'
        },
        {
          label: tempDesc.type,
          key: 'type'
        },
        {
          label: '状态',
          key: 'status'
        },
        {
          label: tempDesc.icon,
          key: 'icon'
        },
        {
          label: '菜单层级',
          key: 'level'
        }
      ],
      menuList: [],
      menuTree: [],// 树形菜单
      dialogFormVisible: false,
      dialogStatus: '',
      titleMap: {
        update: '编辑',
        create: '增加'
      },
      form: {
        'admin_account': undefined,
        'password': undefined,
        'sociaty_no': undefined,
      },
      menuTypeOptions,
      menuStatus,
      optionsStatus: [{ value: undefined, label: '全部状态' }, { value: '1', label: '正常' }, { value: '2', label: '封禁' }],
      optionsLevel: [{ value: undefined, label: '全部类别' }, { value: '1', label: '公会' }, { value: '2', label: '厅' }],
      rules: {
        admin_account: [
          { required: true, message: '请输入管理员姓名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入管理员密码', trigger: 'blur' }
        ],
        sociaty_no: [
          { required: true, message: '请输入厅的号码', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // if (this.global_checkBtnPermission(['sys:menu:add', 'sys:menu:addsub', 'sys:menu:edit', 'sys:menu:delete'])) {
    //   this.columns.push({ label: '操作', key: 'operation', width: 320 })
    // }
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      let urlData = '?';
      if (this.listQuery.page) {
        urlData = urlData + `page=${this.listQuery.page}&`
      }
      if (this.listQuery.perPage) {
        urlData = urlData + `perPage=${this.listQuery.perPage}`
      }
      if (this.listQuery.relations) {
        urlData = urlData + `&relations=${this.listQuery.relations}`
      }
      if (this.listQuery.type) {
        urlData = urlData + `&type=${this.listQuery.type}`
      }
      if (this.listQuery.start_at) {
        urlData = urlData + `&start_at=${this.listQuery.start_at}`
      }
      if (this.listQuery.end_at) {
        urlData = urlData + `&end_at=${this.listQuery.end_at}`
      }

      treeMenu(urlData).then(response => {
        this.menuList = response.data.list
        this.total = response.data.meta.total;

        this.listLoading = false
      })
    },
    getExcel() {
      // axios.get('http://dev-admin-api.yutangwl..com/sociaty/income/export?', {responseType: 'arraybuffer'}).then(res => {
      //   fileDownload(res.data, 'xxx.xls')
      // })
      // return;
      let urlData = '?';
      if (this.listQuery.relations) {
        urlData = urlData + `&relations=${this.listQuery.relations}`
      }
      if (this.listQuery.start_at) {
        urlData = urlData + `&start_at=${this.listQuery.start_at}`
      }
      if (this.listQuery.end_at) {
        urlData = urlData + `&end_at=${this.listQuery.end_at}`
      }
      urlData === '?' ? '' : urlData
      getExcel(urlData).then(response => {
        this.$notify({
          type: 'success',
          message: '操作成功',
          position: 'bottom-right',
          showClose: false,
          duration: 3000
        });
      })
    },
    getExcelA() {
      event.preventDefault();//使a自带的方法失效，即无法调整到href中的URL
      let url = 'http://dev-admin-api.yutangwl.com/sociaty/income/export';   //请求的URl
      let xhr = new XMLHttpRequest();		//定义http请求对象
      xhr.open("get", url, true);
      xhr.setRequestHeader("Content-type", "application/json");
      xhr.setRequestHeader("token", getToken());
      xhr.send();
      xhr.responseType = "blob";  // 返回类型blob
      xhr.onload = function() {   // 定义请求完成的处理函数，请求前也可以增加加载框/禁用下载按钮逻辑
        if (this.status === 200) {
          let blob = this.response;
          //alert(this.readyState);
          //alert(xhr.getAllResponseHeaders());
          xhr.getResponseHeader("content-disposition")
          let temp = xhr.getResponseHeader("content-disposition").split(";")[1].split("filename=")[1];
          let fileName = decodeURIComponent(temp);
          //let hh = xhh.getResponseHeader("fileName");

          //let fileName = this.response.headers["content-disposition"].split(";")[1].split("filename=")[1];
          xhr.getResponseHeader("content-disposition")
          let reader = new FileReader();
          reader.readAsDataURL(blob);  // 转换为base64，可以直接放入a标签href
          reader.onload = function(e) {

            // 转换完成，创建一个a标签用于下载
            let a = document.createElement('a');
            a.download = fileName + ".xlsx";			//自定义下载文件名称
            a.href = e.target.result;
            $("body").append(a);    // 修复firefox中无法触发click
            a.click();
            //$(a).remove();
          }
        } else {
          alert("出现了未知的错误!");
        }
      }
    },
    handleCreate(row) {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    handleUpdate(row) {
      this.form = []
      // this.form = Object.assign({}, row) // copy obj  此方法在这里暂时不能使用，会出错 -> 有多余参数
      this.form.admin_account = row.admin_account
      this.form.password = row.password
      this.form.sociaty_no = row.sociaty_no

      this.dialogStatus = 'update'
      this.dialogFormVisible = true

      let parentNode = this.findTreeNode(row.parentId)
      if (parentNode) {
        this.form.parent_id = parentNode.menu_name
      }

      this.form = Object.assign({}, this.form)
    },
    handleDelete(row) {
      deleteMenu(row.sociaty_id).then(response => {
        if (response.code === 200) {
          this.getList()
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          });
        }
      })
    },
    submitForm() {
      // this.form.parent_id = undefined;
      this.$refs['dataForm'].validate(valid => {
        let md5PW = md5(this.form.password)
        this.form.password = md5PW
        if (valid && this.dialogStatus === 'create') {
          saveMenu(this.form).then(response => {
            if (response.code === 200) {
              this.getList()
              this.$notify({
                type: 'success',
                message: '操作成功',
                position: 'bottom-right',
                showClose: false,
                duration: 3000
              });
              this.dialogFormVisible = false
            } else {
              this.submitFail(123456)
              this.$message({
                message: response.message,
                type: 'error'
              });
            }
          })
        } else if (valid && this.dialogStatus === 'update') {
          updateMenu(this.form).then(response => {
            if (response.code === 200) {
              this.getList()
              this.$notify({
                type: 'success',
                message: '操作成功',
                position: 'bottom-right',
                showClose: false,
                duration: 3000
              });
              this.dialogFormVisible = false
            } else {
              this.$message({
                message: response.message,
                type: 'error'
              });
            }
          })
        }
      })
    },
    cache() {
      cacheMenu(this.form).then(response => {
        this.$notify({
          type: 'success',
          message: '操作成功',
          position: 'bottom-right',
          showClose: false,
          duration: 3000
        });
      })
    },
    findTreeNode(id) {
      let node = this._.find(this.menuList, { id: parseInt(id) })
      return node
    },
    handleExpand() {
      this.expandAll = !this.expandAll
      this.expandAllTitle = this.expandAll ? '折叠全部' : '展开全部'
    },
    resetForm() {
      this.form = {
        'admin_account': undefined,
        'password': undefined,
        'sociaty_no': undefined,
      }
    },
    // 监听dialog关闭时的处理事件
    handleDialogClose() {
      if (this.$refs['dataForm']) {
        this.$refs['dataForm'].clearValidate() // 清除整个表单的校验
      }
    },
    handleAvatarSuccess(res, file) {

    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }

      this.form.avatar = file
      // return isJPG && isLt2M;
    },
  }
}
</script>
<style lang="scss" rel="stylesheet/scss" scoped>
.mb {
  margin-bottom : 10px;
}

.app-container /deep/ .el-date-editor.el-input {
  margin-bottom : 10px;
}

.app-container /deep/ .el-select {
  margin-bottom : 10px;
}
</style>
